package com.zeyi.chat.manager;

import com.zeyi.chat.dto.Message;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author zeyi
 */
public class SocketManager {
    public static HashMap<Integer, Socket> socketMap = new HashMap<>();

    public static void addSocket(Integer id, Socket socket) {
        socketMap.put(id, socket);
    }

    public static Socket getSocket(Integer id) {
        return socketMap.get(id);
    }

    public static void removeSocket(Integer id) {
        socketMap.remove(id);
    }

    public static void send(Integer receiverId, Message message) {
        Socket socket = socketMap.get(receiverId);
        if (socket == null) return;
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void send(Socket socket, Message message) {
        if (socket == null) return;
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
